import { h, ref } from "vue"
const keepaliveComponentsMap = new Map()

export function useKeepAlive(){
    const cacheRoutes = ref([])
    /**
     * 存储组件
     */
    const useSetComponent = (path, com) => {
        const component = {
            name: path,
            render() {
              return h(com);
            },
        };
        cacheRoutes.value.push(path);
        keepaliveComponentsMap.set(path, component);
        return component;
    }
    /**
   * 删除
   */
  const useDeleteComponent = (path) => {
    keepaliveComponentsMap.delete(path);
    // index
    const idx = cacheRoutes.value.findIndex((item) => item === path);
    if (idx !== -1) {
      cacheRoutes.value.splice(idx, 1);
    }
  };
    /**
     * 获取组件
     */
    const useGetComponent = (path) => keepaliveComponentsMap.get(path)
    /**
     * 判断组件是否存在
     */
    const useHasComponent = (path) => keepaliveComponentsMap.has(path)
    /**
   * 返回路由的组件
   */
  const useFormatComponent = (component, route) => {
    if (component) {
        // 当前组件的路由 path
      const path = route?.path;
      const afterComponent = useHasComponent(path) ? useGetComponent(path) : useSetComponent(path, component);
      return h(afterComponent);
    }
  };

  return {
    useFormatComponent,
    useDeleteComponent,
    cacheRoutes
  }



}